package com.example.demo.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.example.demo.config.AlipayConfig;
import com.example.demo.pojo.*;
import com.example.demo.service.*;
import com.example.demo.utils.GetDay;
import com.example.demo.utils.GetRandom;
import com.example.demo.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@ComponentScan
public class BookController {
    @Autowired
    private BookService bookService;
    @Autowired
    private RoomTypeService roomTypeService;
    @Autowired
    private UserService userService;
    @Autowired
    private CustomerService customerService;

    @Autowired
    private BillService billService;




    @Autowired
    private MailUtil mailUtil ;

    @Transactional
    @RequestMapping("/admin-book")
    public String getAdminBookList(Model model,String currentPage)throws Exception{
        Page pageBooks = bookService.pageBooks(currentPage);
        List<Book> bookList = pageBooks.getShowBooks();
        model.addAttribute("bookList",bookList);
        model.addAttribute("pageBooks",pageBooks);
        model.addAttribute("state",0);

        return "/admin/admin-book";
    }

    /**
     * 订单关键词查询
     * @param start
     * @param end
     * @param ddd
     * @param custNum
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("/admin-get")
    public ModelAndView getAdminBy(String start, String end, String ddd, String custNum)throws Exception{
        String show = bookService.getShow(start, end, ddd, custNum);
        System.out.println(show);
        if(start.equals("") && end.equals("") && ddd.equals("no") && custNum.equals("")){
            //数据都为空，提醒
            return new ModelAndView("redirect:/admin-get-no");
        }else{
            if(start.equals("") || end.equals("")){
                //无起始日和截止日，不用判断
                List<Book> bookList = bookService.pageBooksBy(start,end,ddd,custNum);
                if(bookList.size()==0){
                    System.out.println("bucunzai");
                    return new ModelAndView("redirect:/admin-get-bucunzai");
                }else{
                    System.out.println("fuck");
                    ModelAndView mav = new ModelAndView();
                    mav.addObject("bookList",bookList);
                    mav.addObject("state",1);
                    mav.addObject("show",show);
                    mav.setViewName("/admin/admin-book-select");
                    return mav;
                }
            }else{
                //有了起始日和截止日，进行判断
                if(panduanDate(start,end)){
                    List<Book> bookList = bookService.pageBooksBy(start,end,ddd,custNum);
                    if(bookList.size()==0){
                        System.out.println("bucunzai");
                        return new ModelAndView("redirect:/admin-get-bucunzai");
                    }else{
                        System.out.println("fuck");
                        ModelAndView mav = new ModelAndView();
                        mav.addObject("bookList",bookList);
                        mav.addObject("state",1);
                        mav.addObject("show",show);
                        mav.setViewName("/admin/admin-book-select");
                        return mav;
                    }
                }else {
                    return new ModelAndView("redirect:/admin-get-riqicuowu");
                }
            }
        }
    }

    @RequestMapping("/admin-get-no")
    @ResponseBody
    public String admingetno() {
        return  "<script type='text/javascript'>alert('请输入关键词再进行查询!');window.location='/admin-book?currentPage=1'</script>";
    }
    @RequestMapping("/admin-get-bucunzai")
    @ResponseBody
    public String admingetbucunzai() {
        return  "<script type='text/javascript'>alert('不存在这样的订单，请重新输入!');window.location='/admin-book?currentPage=1'</script>";
    }
    @RequestMapping("/admin-get-riqicuowu")
    @ResponseBody
    public String admingetriqicuowu() {
        return  "<script type='text/javascript'>alert('起始日要小于截止日，请重新输入!');window.location='/admin-book?currentPage=1'</script>";
    }

    /**
     * 订单删除修改
     * @param model
     * @param bookID
     * @return
     * @throws Exception
     */
    @Transactional
    @RequestMapping("/admin-book-xiugai")
    public String getupdateByBookID(Model model,String bookID)throws Exception{
        //这个是用于获得book便于查看页面
        Book book = bookService.getBookByBookID(Integer.parseInt(bookID));
        String billState = billService.getbillStateByBookID(bookID);
        model.addAttribute("billState",billState);
        model.addAttribute("book",book);
        return "/admin/admin-book-xiugai";
    }
    @Transactional
    @RequestMapping("/admin-book-update")
    @ResponseBody
    public String updateByBookID(Integer  bookID, String custNum, Integer roomID, Date createTime, String arriveDate,
                                 String leaveDate, String remark,String bookState,String billState) throws ParseException {
        int custID = bookService.getcustIDByBookID(bookID);
        if(customerService.checkCustNumByCustID(custNum,custID) ==null){
            if(panduanDate(arriveDate,leaveDate)){
                //修改判断
                int flag = bookService.updateBookByBookID1(bookID,custNum,roomID,createTime,arriveDate,leaveDate,remark,bookState);
                int flag1 = billService.updateBillStateByBookID(bookID,billState);
                if (flag == 1 && flag1 ==1)
                    return "<script type='text/javascript'>alert('修改成功');window.location='/admin-book?currentPage=1'</script>";
                else
                    return "<script type='text/javascript'>alert('修改失败');window.location='/admin-book?currentPage=1'</script>";
            }else{
                return "<script type='text/javascript'>alert('起始日要小于截止日，修改出错!');window.location='/admin-book?currentPage=1'</script>";
            }
        }else{
            return "<script type='text/javascript'>alert('证件号重复！请重新输入');window.location='/admin-book?currentPage=1'</script>";
        }

    }
    @Transactional
    @RequestMapping("/admin-book-delete")
    @ResponseBody
    public String deleteBookByBookId(String bookID) {
        int flag = bookService.deleteBookByBookId(Integer.parseInt(bookID));
        if (flag ==1)
            return "<script type='text/javascript'>alert('删除成功');window.location='/admin-book?currentPage=1'</script>";
        else
            return "<script type='text/javascript'>alert('删除失败');window.location='/admin-book?currentPage=1'</script>";
    }

    @RequestMapping("/admin-book-delete-tj")
    @ResponseBody
    public String delete_tj(String bookID) {
        return "<script type='text/javascript'> var flag=  " +
                "window.confirm('确认删除吗');" +
                "if(flag == true)  " +
                 "window.location='/admin-book-delete?bookID="+ bookID +
                "';else  " +
                "  window.location='/admin-book?currentPage=1' ;</script>";
    }

    /**
     * 同意预订操作
     * @param bookID
     * @return
     */
    @Transactional
    @RequestMapping("/admin-book-tongyi")
    @ResponseBody
    public String tongyiBook(String bookID) {
        //预订成功,创建账单bill ,发送邮件，根据typeID随机给一个房间号
        int[] roomIDList = bookService.getRoomIDbyBookID(bookID);
        Random random = new Random();
        int roomIDnum = random.nextInt(roomIDList.length-1);
        int roomID = roomIDList[roomIDnum];
System.out.println("cnm :" + bookID);
        int flag = bookService.updateBookStateByBookId(1,Integer.parseInt(bookID));

        if (flag ==1){
            String email = bookService.getBookEmail(bookID);
            Book book = bookService.getBookByBookID(Integer.parseInt(bookID));
            book.setRoomID(roomID);
            if(billService.getbillBybookID(bookID)==null){
                billService.addBill(book);
                bookService.updateRoomIDByBookID(roomID,bookID);
            }else {
                billService.updateBillStateByBookID(Integer.parseInt(bookID),"0");
                billService.updateRoomIDByBookID(roomID,bookID);
                bookService.updateRoomIDByBookID(roomID,bookID);
            }
            String custName= bookService.getBookCustName(bookID);
            mailUtil.sendGood(email,book,custName);
           return  "<script type='text/javascript'>alert('预订成功');window.location='/admin-book?currentPage=1'</script>";
        }else{
            return  "<script type='text/javascript'>alert('预订失败');window.location='/admin-book?currentPage=1'</script>";
        }


    }
    @RequestMapping("/admin-book-ty")
    @ResponseBody
    public String tyBook(String bookID) {
        return "<script type='text/javascript'> var flag=  " +
                "window.confirm('确认通过预订吗');" +
                "if(flag == true)  " +
                "window.location='/admin-book-tongyi?bookID="+ bookID +
                "';else  " +
                "  window.location='/admin-book?currentPage=1' ;</script>";
    }

    @RequestMapping("/admin-book-rf")
    @ResponseBody
    public String refuseBook(String bookID) {
        return "<script type='text/javascript'> var flag=  " +
                "window.confirm('确认拒绝预订吗');" +
                "if(flag == true)  " +
                "window.location='/admin-book-refuse?bookID="+ bookID +
                "';else  " +
                "  window.location='/admin-book?currentPage=1' ;</script>";
    }
    @Transactional
    @RequestMapping("/admin-book-refuse")
    @ResponseBody
    public String rfBook(String bookID) {
        //发送拒绝邮箱并设置成不可见订单---订单状态为4
            System.out.println(bookID);
        int flag = bookService.updateBookStateByBookId(4,Integer.parseInt(bookID));
        if (flag ==1){
            String email = bookService.getBookEmail(bookID);
                System.out.println(email);
            Book book = bookService.getBookByBookID(Integer.parseInt(bookID));
                System.out.println(book.getCustNum());
            String custName= bookService.getBookCustName(bookID);
                System.out.println(custName);
            mailUtil.sendBad(email,book,custName);
            return "<script type='text/javascript'>alert('拒绝订单成功！');window.location='/admin-book?currentPage=1'</script>";
        } else
            return "<script type='text/javascript'>alert('失败');window.location='/admin-book?currentPage=1'</script>";
    }
//-*---------------------------------------------------------
    @RequestMapping("/Admin/addBook")
    @ResponseBody
    public String addBook(String custNum, int roomID, Date bookTime, Date bookCheckinTime, int bookDay, int bookState) {
        int flag = bookService.addBook(custNum,roomID,bookTime,bookCheckinTime,bookDay,bookState);
        if (flag ==1)
            return "addBook添加成功";
        else
            return "添加失败";
    }

    public boolean panduanDate(String date1,String date2) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println(date1+date2);
        if(date1 !=null && date2 !=null) {
            Date Startdate = sdf.parse(date1);
            Date enddate = sdf.parse(date2);
            return Startdate.before(enddate);
        }
        return true;
    }




    /**
     * 预订操作
     * @param session：获取房型号
     * @param typeID ：根据房型号找房型信息
     * @return
     */
    @Transactional
    @RequestMapping(value = "/user-book", method = RequestMethod.GET)
    public String getuserbook(HttpSession session, @RequestParam("typeID") int typeID,Map map) {
        session.setAttribute("typeID",typeID);
        String arriveDate=(String) session.getAttribute("arriveDate");
        String leaveDate=(String)session.getAttribute("leaveDate");
        GetDay getDay =new GetDay();
        int nDay=getDay.nDaysBetweenTwoDate(arriveDate,leaveDate);
        RoomType roomType=roomTypeService.findById(typeID);
        Float price=roomType.getPrice()*nDay;
        String username = (String) session.getAttribute("username");
        User user =userService.getUserByUsername(username);
        Customer customer = customerService.findByUID(user.getuID());
        if(customer==null){

            map.put("customer",customer);
            map.put("msg","没有客户信息,请先添加客户信息");
            return "user-addCust";
        }
        else {
            map.put("roomType",roomType);
            map.put("custNum",customer.getCustNum());
            map.put("custPhone",customer.getCustPhone());
            map.put("price",price);
            return "user-book";
        }

    }
//    @RequestMapping(value = "/user-book", method = RequestMethod.POST)
//    public String custbook(Book book, HttpSession session, Map map){
//        int typeID= Integer.valueOf(String.valueOf(session.getAttribute("typeID")));
//        Date date = new Date();
//        book.setTypeID(typeID);
//        book.setBookState(0);
//        book.setCreateTime(date);
//        RoomType roomType=roomTypeService.findById(typeID);
//
//        if (StringUtils.isEmpty(book.getArriveDate())) {
//            map.put("msg","日期选择不能为空");
//        }
//        if (StringUtils.isEmpty(book.getCreateTime())) {
//            map.put("msg","日期选择不能为空");
//        }
//        if (StringUtils.isEmpty(book.getCustNum())) {
//            map.put("msg","身份号不能为空");
//        }
//        if (StringUtils.isEmpty(book.getCustPhone())) {
//            map.put("msg","手机号不能为空");
//
//        }
//        else {
//            bookService.addCustBook(book);
//            roomType.setAvilableNum(roomType.getAvilableNum()-1);
//            roomType.setBookNum(roomType.getBookNum()+1);
//            roomTypeService.updateroomNum(roomType);
//            session.setAttribute("book",book);
//        }
//        return "user-book";
//    }
    @Transactional
    @RequestMapping(value = "/user-book")
    public void custbook(Book book, HttpSession session, Map map, @RequestParam("money")String money, HttpServletResponse response)throws IOException {
        int typeID= Integer.valueOf(String.valueOf(session.getAttribute("typeID")));
        Date date = new Date();
        book.setTypeID(typeID);
        book.setBookState(0);
        book.setCreateTime(date);
        RoomType roomType=roomTypeService.findById(typeID);
        String username = (String) session.getAttribute("username");
        User user =userService.getUserByUsername(username);
        Customer customer = customerService.findByUID(user.getuID());
        book.setCustID(customer.getCustID());
        GetRandom getRandom =new GetRandom();
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no =getRandom.doOrderNum();
        //付款金额，必填
        String total_amount = money;
        //订单名称，必填
        String subject = roomType.getTypeName();
        //商品描述，可空
        String body = "";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        book.setOut_trade_no(getRandom.doOrderNum());
        book.setMoney(money);
        session.setAttribute("book",book);
        session.setAttribute("roomType",roomType);
        response.setContentType("text/html;charset=" + AlipayConfig.charset);
        response.getWriter().write(form);//直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }
    @Transactional
    @RequestMapping(value="/success",method=RequestMethod.GET)
    public String logout(HttpSession session,Map map){
        try{
            Book book = (Book)session.getAttribute("book");
            bookService.addCustBook(book);
            map.put("msgggg","success");
//            return "redirect:/loginSuccess";
        }catch (Exception e){
            map.put("fail","失败");

        }finally {
            return "success";
        }

    }
    @Transactional
    @RequestMapping(value = "/admin-list-book",method = RequestMethod.GET)
    public String listbook(){
        return "admin/admin-list-book";
    }

    @Transactional
    @RequestMapping(value = "/admin-list-booktest",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> listbooktest(@RequestParam(value = "startDate" ,defaultValue ="null")String startDate){
        Map<String,Object> remap =new HashMap<>();
        int typeID;
        String roomname;
        if(startDate.equals("null")){
            Date date =new Date();

            List<RoomType>roomTypes = roomTypeService.getRoomTypeAll();
            List<Integer>lists =new ArrayList<>();
            List<String>roomNames=new ArrayList<>();
            for( RoomType roomType:roomTypes){
                typeID= roomType.getTypeID();
                roomname=roomType.getTypeName();
                List<Book> books=bookService.findAllbooktest(date,typeID);
                lists.add(books.size());
                roomNames.add(roomname);
                remap.put("summ",lists);
                remap.put("roomname",roomNames);
            }
        }else {
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date =format.parse(startDate);
                List<RoomType>roomTypes = roomTypeService.getRoomTypeAll();
                List<Integer>lists =new ArrayList<>();
                List<String>roomNames=new ArrayList<>();
                for( RoomType roomType:roomTypes) {
                    typeID = roomType.getTypeID();
                    roomname = roomType.getTypeName();
                    List<Book> books = bookService.findAllbooktest(date, typeID);
                    lists.add(books.size());
                    roomNames.add(roomname);
                    remap.put("summ", lists);
                    remap.put("roomname", roomNames);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return remap;
    }

    @Transactional
    @RequestMapping(value = "/admin-list-bookmonth",method = RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> listbookmonth(@RequestParam(value = "startmoDate")String startmoDate){
        Map<String,Object> remap =new HashMap<>();
        int typeID;
        String roomname;
        if(startmoDate.equals("null")){
            Date date =new Date();

            List<RoomType>roomTypes = roomTypeService.getRoomTypeAll();
            List<Integer>lists =new ArrayList<>();
            List<String>roomNames=new ArrayList<>();
            for( RoomType roomType:roomTypes){
                typeID= roomType.getTypeID();
                roomname=roomType.getTypeName();
                List<Book> books=bookService.findAllbookmonth(date,typeID);
                lists.add(books.size());
                roomNames.add(roomname);
                remap.put("summ",lists);
                remap.put("roomname",roomNames);
            }
        }else {
            DateFormat format = new SimpleDateFormat("yyyy-MM");
            try {
                Date date =format.parse(startmoDate);
                List<RoomType>roomTypes = roomTypeService.getRoomTypeAll();
                List<Integer>lists =new ArrayList<>();
                List<String>roomNames=new ArrayList<>();
                for( RoomType roomType:roomTypes) {
                    typeID = roomType.getTypeID();
                    roomname = roomType.getTypeName();
                    List<Book> books = bookService.findAllbookmonth(date, typeID);
                    lists.add(books.size());
                    roomNames.add(roomname);
                    remap.put("summ", lists);
                    remap.put("roomname", roomNames);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return remap;
    }
}

